package com.macro.mall.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Random;

/**
 */
@Configuration
public class SnowflakeAutoConfig {

    private static final Logger logger = LoggerFactory.getLogger(SnowflakeAutoConfig.class);

    private static final Random RANDOM = new Random();

    private final static String SERVER_EVN_IDENTITY_KEY = "CONTAINER_PODIP";

    /**
     * 初始化snowflakeIdWorker
     */
    @Bean
    public SnowflakeIdworker snowflakeIdWorker() {
        Snowflake snowflake = new Snowflake();
        snowflake.setDatacenterId(RANDOM.nextInt(32));
        setWorkerId(snowflake);
        return new SnowflakeIdworker(snowflake);
    }

    /**
     * 为相同服务设置不同的idworker
     * 如果是dev环境，暂时不要setworkId，本地没有配置SERVER_EVN_IDENTITY_KEY这个系统变量，如果需要测试，
     * 则需要在本地os中配置对应的系统变量，该变量运维人员在云实例上配置的是一个网段内唯一的ip地址
     */
    private void setWorkerId(Snowflake snowflake) {
        int randomWorkerId = RANDOM.nextInt(32);
        snowflake.setWorkerId(randomWorkerId);
    }

}
